/* Copyright 2009-2010 Denis Giroto. All rights reserved. Use is subject to license terms. */
package br.ucb.tcc.swing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import thinlet.swing.app.AppFrame;
import thinlet.swing.app.TipManager;
import thinlet.swing.app.UIUtilities;
import thinlet.swing.border.LineBorder;
import thinlet.swing.container.MenuList;
import thinlet.swing.container.SplitPane;
import thinlet.swing.container.ToolFooter;
import thinlet.swing.table.Table;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.TwitterException;
import br.ucb.tcc.negocio.TwitterBean;
import br.ucb.tcc.utils.Constantes;
import br.ucb.tcc.utils.FileUtils;

/**
 * @author italoricci
 *
 */
public class Main extends AppFrame implements ChangeListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private SplitPane splitPane;
	private JScrollPane scrollPane;
	private Table<String> lista;
	

	/**
	 * 
	 * Classe que rodar‡ o projeto
	 * 
	 * 
	 */
	public Main() {
		try {
			setTitle("Integração com Twitter");
			setIconImage("icon/twitter-icon-pack.jpg");
			JPanel left = new JPanel(new BorderLayout());
			left.setBorder(new LineBorder(new Color(0xaaaaaa), 0, 0, 0, 1));
			MenuList menuList = new MenuList();
			menuList.addChangeListener(this);
			menuList.addGroup("Twitter");
			menuList.addSeparator();
			menuList.add(createPageLink("Buscar perfil por nome", BuscarPorUsuarioPanel.class));
			menuList.add(createPageLink("Buscar perfil por Tweet/RT", BuscarUsuarioPorArgumentoPanel.class));
			menuList.add(createPageLink("Enviar Mensagem Direta", EnviarMensagemFrame.class));
			menuList.addSeparator();
			menuList.addGroup("Banco");
			menuList.add(createPageLink("Pesquisar usuários", BuscarUsuarioBancoPanel.class));
			menuList.add(createPageLink("Listagem de relações", ListarRelacoesBancoPanel.class));
			menuList.addSeparator();
			left.add(menuList, BorderLayout.CENTER);
			ToolFooter toolPanel = new ToolFooter();
			toolPanel.add(Box.createHorizontalGlue());
			toolPanel.setBorder(new LineBorder(new Color(0xaaaaaa), 1, 0, 0, 0));
			left.add(toolPanel, BorderLayout.SOUTH);
			JPanel content = new JPanel(new BorderLayout());
			URL imgsrc = Main.class.getResource("icon/twitter-banner.jpg");
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
			content.add(new JLabel("<html><body style=\"margin: 0 8px;\">" + "<table><tr><td>" + "<img width='800' height='100' src='" + imgsrc + "'></img>" + "</td></tr></table><br/><h4>Seja Bem Vindo, " + TwitterBean.obterNome() + ". Veja o que est� acontecendo na sua timeLine : " + dateFormat.format(new Date()) +  " . </body></html>"), BorderLayout.NORTH);
			content.add(jScrollPane(), BorderLayout.CENTER);
			splitPane = new SplitPane(left, content, JSplitPane.HORIZONTAL_SPLIT);
			toolPanel.add(splitPane.getKnob());
			setContentPane(splitPane);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (TwitterException e) {
			AbstractPanel.mostrarMensagemInformativa(e.getMessage(), "");
		}
	}
	
	/**
	 * @return
	 */
	public JScrollPane jScrollPane () {
		try {
			lista = new Table<String>();
			ResponseList<Status> obterHomeTimeLine = TwitterBean.obterHomeTimeLine();
			for (Status status : obterHomeTimeLine) {
				lista.addItem(status.getUser().getName() + " - " + status.getText());
			}
			scrollPane = new JScrollPane(lista);
			scrollPane.setBorder(BorderFactory.createEmptyBorder());
			add(scrollPane, BorderLayout.CENTER);
			return scrollPane;
		} catch (TwitterException e) {
			AbstractPanel.mostrarMensagemInformativa(e.getMessage(), "Erro");
		}
		return new JScrollPane();
	}
	
	

	/**
	 * @param textId
	 * @param clazz
	 * @return
	 */
	private MenuList.Item createPageLink(String textId, Class<?> clazz) {
		MenuList.Item item = new MenuList.Item(textId);
		item.setToolTipText(textId);
		TipManager.register(item);
		item.putClientProperty(":class", clazz);
		return item;
	}

	/* (non-Javadoc)
	 * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
	 */
	public void stateChanged(ChangeEvent e) {
		MenuList.Item selected = ((MenuList) e.getSource()).getSelected();
		if (selected == null) {
			setPage(new JPanel());
		} else {
			try {
				setPage((JComponent) ((Class<?>) selected.getClientProperty(":class")).newInstance());
			} catch (Exception exc) {
				throw new RuntimeException(exc);
			}
		}
	}

	/**
	 * @param content
	 */
	private void setPage(JComponent content) {
		while (splitPane.getComponentCount() > 1)
			splitPane.remove(1);
		splitPane.add(content);
		splitPane.revalidate();
	}

	/* (non-Javadoc)
	 * @see thinlet.swing.app.AppFrame#init()
	 */
	protected void init() {
	}

	/* (non-Javadoc)
	 * @see thinlet.swing.app.AppFrame#showAbout()
	 */
	protected void showAbout() {
		JPanel panel = new JPanel(new BorderLayout(0, 8));
		panel.add(new JLabel(UIUtilities.getIcon(getClass(), "icon/twitter-banner.jpg")), BorderLayout.CENTER);
		panel.add(new JLabel("Integração com o Twitter", JLabel.CENTER), BorderLayout.SOUTH);
		setContentPane(panel); // ...
	}

	/* (non-Javadoc)
	 * @see thinlet.swing.app.AppFrame#close()
	 */
	protected boolean close() {
		return true;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String valorDefault = FileUtils.lerValorProperties(Constantes.PATH, Constantes.ARQUIVO_LOGIN,  "logado");
		if (valorDefault != null && valorDefault.equalsIgnoreCase(Constantes.LOGADO)) {
			String consumerKey = FileUtils.lerValorProperties(Constantes.PATH, Constantes.ARQUIVO_LOGIN,  "consumer");
			String consukerKeySecret = FileUtils.lerValorProperties(Constantes.PATH, Constantes.ARQUIVO_LOGIN,  "consumerSecret");
			TwitterBean.autentica(consumerKey, consukerKeySecret);
			iniciarAplicacao();
		} else {
			InformacoesLoginDialog informacoesLoginPanel = new InformacoesLoginDialog();
			informacoesLoginPanel.setVisible(true);
			iniciarAplicacao();
		}
	}

	private static void iniciarAplicacao() {
		Main m = new Main();
		m.showFrame(1120, 600); // 800, 600
	}

	/* (non-Javadoc)
	 * @see thinlet.swing.app.AppFrame#showPreferences()
	 */
	protected void showPreferences() {
		JComponent comp = (JComponent) getRootPane();
		int w = comp.getWidth(), h = comp.getHeight();
		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
		comp.paint(image.getGraphics());
		BufferedImage small = new BufferedImage(w * 3 / 4, h * 3 / 4, BufferedImage.TYPE_INT_ARGB);
		small.getGraphics().drawImage(image.getScaledInstance(w * 3 / 4, h * 3 / 4, Image.SCALE_SMOOTH), 0, 0, null);
		try {
			String home = System.getProperty("user.home");
			ImageIO.write(small, "png", new File(home, "screenshot.png"));
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
